package chatBot.service.impl;

import chatBot.entity.Order;
import chatBot.service.OrderService;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public void saveOrder(Order order) {
        String sql = "INSERT INTO blog_order (order_id, user_id, commodity_id, pay_type, status, create_time) VALUES (?, ?, ?, ?, ?, ?)";
        jdbcTemplate.update(sql, order.getOrderId(), order.getUserId(), order.getCommodityId(), order.getPayType(), order.getStatus(), order.getCreateTime());
    }

    @Override
    public void updateOrderStatus(Long orderId, int status, Date payTime) {
        String sql = "UPDATE blog_order SET status = ?, pay_time = ? WHERE order_id = ?";
        jdbcTemplate.update(sql, status, payTime, orderId);
    }

    @Override
    public Order findOrderById(Long orderId) {
        String sql = "SELECT * FROM blog_order WHERE order_id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{orderId}, new RowMapper<Order>() {
            @Override
            public Order mapRow(ResultSet rs, int rowNum) throws SQLException {
                Order order = new Order();
                order.setOrderId(rs.getLong("order_id"));
                order.setUserId(rs.getLong("user_id"));
                order.setCommodityId(rs.getLong("commodity_id"));
                order.setPayType(rs.getInt("pay_type"));
                order.setStatus(rs.getInt("status"));
                order.setCreateTime(rs.getDate("create_time"));
                order.setPayTime(rs.getDate("pay_time"));
                return order;
            }
        });
    }
}
